package com.gitee.feizns.quickstart.mybatis.plus.validation.validator;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.TableInfo;
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.gitee.feizns.dynamic.Lists;
import com.gitee.feizns.dynamic.Objs;
import com.gitee.feizns.dynamic.reflect.Constructors;
import com.gitee.feizns.quickstart.mybatis.plus.utils.WrapperUtils;
import com.gitee.feizns.quickstart.mybatis.plus.validation.constraints.ExistId;
import com.gitee.feizns.quickstart.validation.validator.AbstractConstraintValidator;

import javax.validation.ConstraintValidatorContext;
import java.io.Serializable;
import java.util.List;

/**
 * 存在指定的ID
 * @author feizns
 * @since 2023/2/5
 */
public class ExistsIdConstraintValidator extends AbstractConstraintValidator<ExistId, Object> {

    /**
     * 账号正则
     */
    private ExistId annotation;

    @Override
    public void initialize(ExistId annotation) {
        super.initialize(annotation);
        this.annotation = annotation;
    }

     @Override
    public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
         List<? extends Serializable> idList = Lists.of(Objs.cast(Objs.toArray(o), Serializable[]::new));
         TableInfo info = TableInfoHelper.getTableInfo(annotation.value());
         @SuppressWarnings("unchecked")
         Model<Model<?>> model = (Model<Model<?>>) Constructors.newInstance(annotation.value());
         QueryWrapper<Model<?>> query = Wrappers.query();
         return model.selectCount(WrapperUtils.eqOrIn(query, info.getKeyColumn(), idList)) == idList.size();
    }

}